﻿using System;
using System.IO;
using System.Text;

namespace La.Code
{
    /// <summary>
    /// 文件操作类 windows from
    /// </summary>
    public class FileHelperFrom
    {
        private Encoding defaultEncoding = Encoding.UTF8;


        /// <summary>
        /// 剪贴文件
        /// </summary>
        /// <param name="formPath"></param>
        /// <param name="toPath"></param>
        public void MoveToFileStream(String formPath, String toPath)
        {
            try
            {

                FileStream fs = new FileStream(formPath, FileMode.Open, FileAccess.Read);
                Byte[] mFileByte = new Byte[fs.Length];
                fs.Read(mFileByte, 0, mFileByte.Length);
                fs.Flush();
                fs.Close();

                //文件流转
                String tP = toPath.Substring(0, toPath.LastIndexOf('/'));
                if (!Directory.Exists(tP))
                {
                    DirectoryInfo di = Directory.CreateDirectory(tP);
                }

                //定义并实例化一个内存流，以存放提交上来的字节数组。
                MemoryStream m = new MemoryStream(mFileByte);
                //定义实际文件对象，保存上载的文件。
                FileStream f = new FileStream(toPath, FileMode.Create);
                //把内内存里的数据写入物理文件
                m.WriteTo(f);
                m.Flush();
                m.Close();
                f.Flush();
                f.Close();

            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 剪贴文件
        /// </summary>
        /// <param name="formPath"></param>
        /// <param name="toPath"></param>
        public void MoveToFile(String formPath, String toPath)
        {
            try
            {
                FileInfo file = new FileInfo(formPath);
                String tP = toPath.Substring(0, toPath.LastIndexOf('/'));
                if (!Directory.Exists(tP))
                {
                    DirectoryInfo di = Directory.CreateDirectory(tP);
                }
                file.MoveTo(toPath);

            }
            catch (Exception)
            {
                throw;
            }
        }


        /// <summary>
        /// 获取文件夹下面大小
        /// </summary>
        /// <param name="dirPath"></param>
        /// <returns></returns>
        public long GetDirectoryLength(string dirPath)
        {
            //判断给定的路径是否存在,如果不存在则退出 
            CreateDirectory(dirPath);


            long len = 0; //定义一个DirectoryInfo对象 
            DirectoryInfo di = new DirectoryInfo(dirPath); //通过GetFiles方法,获取di目录中的所有文件的大小 
            foreach (FileInfo fi in di.GetFiles())
            {
                len += fi.Length;
            }
            //获取di中所有的文件夹,并存到一个新的对象数组中,以进行递归 
            DirectoryInfo[] dis = di.GetDirectories();
            if (dis.Length > 0)
            {
                for (int i = 0; i < dis.Length; i++)
                {
                    len += GetDirectoryLength(dis[i].FullName);
                }
            }
            return len;
        }

        //也是利用递归的思想,只不过是通过File类的Exits方法来判断 
        //所给路径中所对应的是否为文件 
        public static long FileSize(string filePath)
        {
            long temp = 0; //判断当前路径所指向的是否为文件 
            if (File.Exists(filePath) == false)
            {
                string[] str1 = Directory.GetFileSystemEntries(filePath);
                foreach (string s1 in str1)
                {
                    temp += FileSize(s1);
                }
            }
            else
            {
                //定义一个FileInfo对象,使之与filePath所指向的文件向关联,
                //以获取其大小
                FileInfo fileInfo = new FileInfo(filePath);
                return fileInfo.Length;
            }
            return temp;
        }



        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="filePath">文件夹的物理路径</param>
        /// <returns></returns>
        public bool CreateDirectory(string filePath)
        {
            try
            {
                if (!Directory.Exists(filePath))
                {
                    DirectoryInfo di = Directory.CreateDirectory(filePath);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="filePath">文件的物理路径</param>
        /// <param name="fileContent">文件的内容</param>
        public bool CreateFile(string filePath, string fileContent)
        {
            try
            {
                if (CreateDirectory(Path.GetDirectoryName(filePath)))
                {
                    Encoding code = defaultEncoding;
                    StreamWriter mySream = new StreamWriter(filePath, false, code);
                    mySream.WriteLine(fileContent);
                    mySream.Flush();
                    mySream.Close();
                    mySream = null;
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取文件内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public string ReadFile(string filePath, Encoding encoding)
        {
            try
            {
                string fileContent = "";
                using (StreamReader sr = new StreamReader(filePath, encoding))
                {
                    fileContent = sr.ReadToEnd();
                }
                return fileContent;
            }
            catch (Exception)
            {
                return "读取文件时产生不可预知的错误。";
            }
        }

        /// <summary>
        /// 获取文件内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public string ReadFile(string filePath)
        {
            return ReadFile(filePath, defaultEncoding);
        }

        /// <summary>
        /// 写文件操作
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileContent"></param>
        /// <param name="isAppend"></param>
        /// <returns></returns>
        public bool WriteFile(string filePath, string fileContent, bool isAppend)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    CreateFile(filePath, "");
                }
                StreamWriter Fso = new StreamWriter(filePath, isAppend);
                Fso.WriteLine(fileContent);
                Fso.Close();
                Fso.Dispose();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public bool DeleteFile(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除文件组
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns>是否全部删除，全部删除则为True,否则为False</returns>
        public bool DeleteFile(string[] filePath)
        {
            bool isAllDelete = true;
            for (int i = 0; i < filePath.Length; i++)
            {
                if (!DeleteFile(filePath[i]))
                {
                    isAllDelete = false;
                }
            }
            return isAllDelete;
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <returns></returns>
        public bool DeleteDirectory(string directoryPath)
        {
            try
            {
                if (Directory.Exists(directoryPath))
                {
                    Directory.Delete(directoryPath);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 读取HTML文件内容
        /// </summary>
        /// <param name="Path">物理路径</param>
        /// <returns></returns>
        public static string ReadHtml(string Path)
        {
            string result = string.Empty;
            if (File.Exists(Path))
            {
                try
                {
                    using (StreamReader sr = new StreamReader(Path, Encoding.GetEncoding("UTF-8")))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                catch (Exception)
                {
                }
            }
            else
            {
                result = "模板不存在!";
            }
            return result;
        }
        /// <summary>
        /// 重命名文件
        /// </summary>
        /// <param name="filePath">文件所在的目录,不要最后那个斜杠例如E:\\Dir\\GG</param>
        /// <param name="oldName">原名称</param>
        /// <param name="newName">修改的名称</param>
        /// <param name="fileType">文件类型 0为文件夹 1是文件</param>
        /// <returns></returns>
        public bool ReNameFile(string filePath, string oldName, string newName, int fileType)
        {
            try
            {
                if (fileType.Equals(0))
                {
                    if (Directory.Exists(filePath + "\\" + oldName))
                    {
                        Directory.Move(filePath + "\\" + oldName, filePath + "\\" + newName.Replace(".", ""));
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    if (File.Exists(filePath + "\\" + oldName))
                    {
                        File.Move(filePath + "\\" + oldName, filePath + "\\" + newName);
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        //对文件生成树
        public StringBuilder fileTree = new StringBuilder();
        int directoryIndex = 0;
        public string rootUrl = "";
        int listIndex = 0;
        public void listFiles(string dir, int level)
        {
            try
            {
                string[] dirs = Directory.GetDirectories(dir);
                foreach (string d in dirs)
                {
                    directoryIndex++;
                    if (d.LastIndexOf("\\") == -1)
                    {
                        fileTree.AppendLine("d.add(" + directoryIndex + "," + level + ",'" + d.Substring(d.LastIndexOf("/") + 1) + "');");
                    }
                    else
                    {
                        fileTree.AppendLine("d.add(" + directoryIndex + "," + level + ",'" + d.Substring(d.LastIndexOf("\\") + 1) + "');");
                    }
                    if (Directory.Exists(d))
                    {
                        listFiles(d, directoryIndex);
                    }

                }

                string[] files = Directory.GetFiles(dir, "*.*htm*");

                foreach (string f in files)
                {

                    directoryIndex++;
                    if (f.LastIndexOf("\\") == -1)
                    {
                        fileTree.AppendLine("filelist[" + listIndex + "]='" + ((f.Replace(rootUrl + "\\", "")).Replace("\\", "/")) + "';");
                        fileTree.AppendLine("d.add(" + directoryIndex + "," + level + ",''" + f.Substring(f.LastIndexOf("/") + 1) + "','javascript: GetFileUrl(filelist[" + listIndex + "]);');");
                    }
                    else
                    {
                        fileTree.AppendLine("filelist[" + listIndex + "]='" + ((f.Replace(rootUrl + "\\", "")).Replace("\\", "/")) + "';");
                        fileTree.AppendLine("d.add(" + directoryIndex + "," + level + ",'" + f.Substring(f.LastIndexOf("\\") + 1) + "','javascript: GetFileUrl(filelist[" + listIndex + "]);');");
                    }
                    listIndex++;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// 只取文件夹名
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="level"></param>
        /// kevin改
        public void listFileName(string dir, int level)
        {
            try
            {
                string[] dirs = Directory.GetDirectories(dir);
                foreach (string d in dirs)
                {
                    directoryIndex++;
                    if (d.LastIndexOf("\\") == -1)
                    {
                        fileTree.AppendLine("d.add(" + directoryIndex + "," + level + ",'" + d.Substring(d.LastIndexOf("/") + 1) + "','javascript: GetFileUrl(filelist[" + listIndex + "]);');");
                    }
                    else
                    {
                        fileTree.AppendLine("filelist[" + listIndex + "]='" + ((d.Replace(rootUrl + "\\", "")).Replace("\\", "/")) + "';");
                        fileTree.AppendLine("d.add(" + directoryIndex + "," + level + ",'" + d.Substring(d.LastIndexOf("\\") + 1) + "','javascript: GetFileUrl(filelist[" + listIndex + "]);');");
                    }
                    listIndex++;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        public static string StringToHtml(string strText)
        {
            string strHtml = strText.Replace(" ", "&nbsp;");
            strHtml = strHtml.Replace("<", "&lt;");
            strHtml = strHtml.Replace(">", "&gt;");
            strHtml = strHtml.Replace("\r\n", "<br />");
            strHtml = strHtml.Replace("\"", "&quot;");
            strHtml = strHtml.Replace("'", "&#39;");
            return strHtml;
        }

        /// <summary>
        /// 获取文件夹中的文件
        /// 向卫东
        /// </summary>
        /// <param name="path">文件夹绝对路径</param>
        /// <param name="searchPattern">文件匹配模式</param>
        /// <returns>返回文件名称</returns>
        public string[] GetFiles(string path, string searchPattern)
        {
            string[] dirs;
            if (searchPattern == "")
            {
                dirs = Directory.GetFiles(path);
            }
            else
            {
                dirs = Directory.GetFiles(path, searchPattern);
            }
            return dirs;
        }
    }
}
